from flask import Blueprint, request, render_template
from .models import *
import random

# 蓝图
blue = Blueprint('user', __name__)


@blue.route('/')
def index():
    return 'index'


@blue.route('/addgrade/')
def addgrade():
    grades = []
    for i in range(10):
        grade = GraderModel()
        grade.name = f'班级{i}-{random.choice(range(1, 10))}'
        grades.append(grade)
    try:
        db.session.add_all(grades)
        db.session.commit()
    except Exception as e:
        print('e:', e)
        db.session.rollback()
        db.session.flush()
    return 'OK'


@blue.route('/addstudent/')
def addstudent():
    students = []
    for i in range(10, 50):
        student = StudentModel()
        student.name = f'学生{i}-{random.choice(range(50, 100))}'
        student.age = int(i * random.randint(10, 50))
        student.grade_id = random.randint(1, 10)
        students.append(student)
    try:
        db.session.add_all(students)
        db.session.commit()
    except Exception as e:
        print('e:', e)
        db.session.rollback()
        db.session.flush()
    return 'OK'


@blue.route('/upstu/')
def updatestu():
    stu = StudentModel.query.first()
    stu.name = '张三'
    db.session.commit()
    return 'OK'


@blue.route('/deletestu/')
def deletestr():
    stu = StudentModel.query.get(2)
    db.session.delete(stu)
    db.session.commit()
    return 'OK'


@blue.route('/deledgrade/')
def deletegrade():
    greade = GraderModel.query.get(2)
    db.session.delete(greade)
    db.session.commit()
    return 'ok'


@blue.route('/selestudent/')
def selestudent():
    stu = StudentModel.query.get(4)
    # print(stu.name, stu.age, stu.grade_id, stu.grade)
    # print(stu.name, stu.age, stu.grade_id, stu.grade)
    #
    grade = GraderModel.query.get(9)
    print(grade.id, grade.name, grade.students)
    for student in grade.students:
        print(student.name, student.age)

    return 'ok'
